package net.wangds.web.filter;

import net.wangds.log.helper.LogHelper;
import net.wangds.web.annotations.AuthType;
import net.wangds.web.components.SpringWebComp;
import net.wangds.web.module.AuthRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebFilter(urlPatterns = "/*", filterName = "authFilter")
//@Order(101)
public class AuthFilter implements Filter, InitializingBean {

    public static final String BEARER = "Bearer ";
    @Value("${net.wangds.web.authfilter.enable:true}")
    private boolean enable;

    @Autowired
    SpringWebComp mmCmpSpringWeb;


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if(enable) {
            if (request instanceof HttpServletRequest) {
                HttpServletRequest req = (HttpServletRequest) request;
                AuthRequest auth = mmCmpSpringWeb.requestAuth(req);

                if(auth!=null&&auth.getType()!= AuthType.NO){

                    HttpServletResponse resp = (HttpServletResponse) response;

                    Object user = loadCurrentUser(req);
                    if(user==null){
                        onNotLogin(req, resp);
                    }
                }

            }
        }

        chain.doFilter(request, response);

    }

    private void onNotLogin(HttpServletRequest req, HttpServletResponse resp) {

    }

    private Object loadCurrentUser(HttpServletRequest req) {
        Object res = null;
        String token = req.getHeader("authorization");

        if(StringUtils.startsWith(token , BEARER)){
            String token_content = token.substring(BEARER.length());
            if(StringUtils.isNotBlank(token_content)){
                return new Object();
            }
        }

        return res;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        LogHelper.info("身份认证过滤器:"+(enable?"启用":"禁用"));
    }
}
